/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.distribution.common.listener;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yami.shop.bean.event.PaySuccessOrderEvent;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.order.PaySuccessOrderOrder;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Arith;
import com.yami.shop.distribution.common.constants.DistributionAudit;
import com.yami.shop.distribution.common.constants.DistributionUserIncomeStateEnum;
import com.yami.shop.distribution.common.constants.DistributionUserStateEnum;
import com.yami.shop.distribution.common.dao.DistributionUserBindMapper;
import com.yami.shop.distribution.common.model.*;
import com.yami.shop.distribution.common.po.DistributionProdPO;
import com.yami.shop.distribution.common.service.*;
import com.yami.shop.distribution.common.vo.DistributionAwardDataVO;
import com.yami.shop.distribution.common.vo.DistributionConfigVO;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.SysConfigService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 支付成功事件
 * @author yami
 */
@Slf4j
@Component("distributionPaySuccessOrderListener")
@AllArgsConstructor
public class PaySuccessOrderListener {

    private final DistributionUserIncomeService distributionUserIncomeService;

    private final SysConfigService sysConfigService;

    private final DistributionBindUserService distributionBindUserService;

    private final DistributionUserService distributionUserService;

    private final DistributionProdService distributionProdService;

    private final DistributionUserWalletService distributionUserWalletService;

    private final DistributionUserWalletBillService distributionUserWalletBillService;

    private final OrderItemService orderItemService;

    private final OrderService orderService;

    private final DistributionUserBindMapper distributionUserBindMapper;




    @EventListener(PaySuccessOrderEvent.class)
    @org.springframework.core.annotation.Order(PaySuccessOrderOrder.DISTRIBUTION)
    public void distributionPaySuccessOrderEvent(PaySuccessOrderEvent event) {
        if(Objects.equals(event.getOrders().get(0).getShopId(),Constant.PLATFORM_SHOP_ID)){
            return;
        }
        // 店铺分销基础设置
        DistributionConfigVO distributionConfigVO = sysConfigService.getSysConfigObject(Constant.DISTRIBUTION_CONFIG, DistributionConfigVO.class);
        // 没有开启分销
        if (distributionConfigVO == null || distributionConfigVO.getDistributionSwitch() == 0) {
            log.debug("平台没有开启分销，跳过分销的流程");
            return;
        }

        // 设置为分销的订单项
        List<OrderItem> distributionOrderItems = new ArrayList<>();
        List<Order> orders = event.getOrders();

        // 不绑定，分享人优先
        if (distributionConfigVO.getAttribution() == 1){
            log.info("过滤没有推广卡号的订单项");
            orders.forEach( item -> {
                List<OrderItem> orderItems = item.getOrderItems();
                orderItems.removeIf(orderItem -> StringUtils.isEmpty(orderItem.getDistributionCardNo()));
                item.setOrderItems(orderItems);
            });
        }
        //过滤封禁分销员推广的分销订单
        if (filtrationOrders(orders, distributionConfigVO)){
            return;
        }



        // 获取所有商品分销状态为1的分销商品
        List<DistributionProd> distributionProds = distributionProdService.listByOrderItems(event.getAllOrderItems());
        List<Long> prodIds = distributionProds.stream().map(DistributionProd::getProdId).collect(Collectors.toList());

        // 所有的订单项
        for (Order order : orders) {
            // 所有的订单项
            List<OrderItem> orderItems = order.getOrderItems();

            boolean isFirstGetBindUser = true;

            DistributionUser oldDistributionUser = null;
            for (OrderItem orderItem : orderItems) {
                // 如果没有状态正常的分销商品则不能进行分销
                if(!prodIds.contains(orderItem.getProdId())){
                    continue;
                }

                // 如果该订单项有分销信息，则将该订单项放入distributionOrderItems中
                if (StrUtil.isNotBlank(orderItem.getDistributionCardNo()) && this.checkSelfShare(orderItem, distributionConfigVO)) {
                    distributionOrderItems.add(orderItem);
                    //处理用户绑定和一二级佣金的
                    doDistribution(oldDistributionUser,orderItem, distributionConfigVO);
                    continue;
                }
                // 初始化用户的旧绑定分销员
                if (isFirstGetBindUser) {

                    isFirstGetBindUser = false;

                    // 查询该用户以前绑定的分享人
                    DistributionUserBind distributionUserBind = distributionUserBindMapper.selectOne(new LambdaQueryWrapper<DistributionUserBind>()
                            .eq(DistributionUserBind::getShopId, Constant.PLATFORM_SHOP_ID)
                            .eq(DistributionUserBind::getState, 1)
                            .eq(DistributionUserBind::getUserId, order.getUserId())
                    );

                    // 该用户以前有绑定分享人
                    if (distributionUserBind != null) {
                        // 查询以前的绑定的用户信息-并赋值
                        oldDistributionUser = distributionUserService.getById(distributionUserBind.getDistributionUserId());
                    }
                }

                if (oldDistributionUser == null) {
                    continue;
                }
                if (!Objects.equals(oldDistributionUser.getState(), 1)) {
                    continue;
                }
                // 设置分销员卡号-用户直接购买商品时，前端没传分销员卡号，需要手动插入
                orderItem.setDistributionCardNo(oldDistributionUser.getCardNo());
                // 将订单项添加到分销项中
                distributionOrderItems.add(orderItem);
                doDistribution(oldDistributionUser,orderItem, distributionConfigVO);

            }
        }
        // 更新分销订单项
        updateOrderItems(distributionOrderItems, orders);
    }

    /**
     * 过滤分销员封禁后推广的分销商品
     * @param orders
     */
    public boolean filtrationOrders(List<Order> orders, DistributionConfigVO distributionConfigVO){
        // 获取分销员卡号
        String carNo = null;
        for (Order order : orders) {
            for (OrderItem orderItem : order.getOrderItems()) {
                if (StringUtils.isNotBlank(orderItem.getDistributionCardNo())){
                    carNo = orderItem.getDistributionCardNo();
                    break;
                }
            }
        }

        // 分享人优先，需要是扫码分销的订单才进行分销
        if (distributionConfigVO.getAttribution() == 1 && StrUtil.isBlank(carNo)) {
            return true;
        }
        // 关系链优先不用传卡号，不需要校验分销员封禁（已绑定的分销员在封禁时会解绑）
        if (StrUtil.isBlank(carNo)) {
            return false;
        }
        DistributionUser distributionUser = distributionUserService.getOne(new LambdaQueryWrapper<DistributionUser>().eq(DistributionUser::getCardNo, carNo));
        if (!Objects.equals(distributionUser.getState(), DistributionUserStateEnum.NORMAL.getValue())) {
            log.info("过滤分销员封禁后推广的分销商品");
            return true;
        }
        return false;
    }

    private void updateOrderItems(List<OrderItem> distributionOrderItems, List<Order> orders) {
        if (CollectionUtils.isNotEmpty(distributionOrderItems)) {
            // 更新订单的分销金额，及订单项的分销金额
            Map<String, List<OrderItem>> orderItemMap = distributionOrderItems.stream().collect(Collectors.groupingBy(OrderItem::getOrderNumber));
            for (String orderNumber : orderItemMap.keySet()) {
                List<OrderItem> orderItems = orderItemMap.get(orderNumber);
                double distributionAmount = 0.0;
                for (OrderItem orderItem : orderItems) {
                    distributionAmount = Arith.add(distributionAmount,Objects.isNull(orderItem.getDistributionAmount())? 0.0:orderItem.getDistributionAmount());
                    distributionAmount = Arith.add(distributionAmount,Objects.isNull(orderItem.getDistributionParentAmount())? 0.0:orderItem.getDistributionParentAmount());
                }
                // 分销金额放进去order里面
                for (Order order : orders) {
                    if(StrUtil.equals(orderNumber,order.getOrderNumber())){
                        order.setDistributionAmount(distributionAmount);
                    }
                }
                orderService.update(new LambdaUpdateWrapper<Order>().set(Order::getDistributionAmount,distributionAmount)
                        .eq(Order::getOrderNumber,orderNumber));
            }
            orderItemService.updateBatchById(distributionOrderItems);
        }
    }

    /**
     * 进行分销操作
     * @param oldShareUser 用户已绑定的分销员
     * @param orderItem 订单项
     * @param distributionConfigVO 分销配置
     */
    private void doDistribution(DistributionUser oldShareUser, OrderItem orderItem, DistributionConfigVO distributionConfigVO){
        DistributionUser shareUser;
        DistributionUser bindUser;

        if (oldShareUser != null && Objects.equals(orderItem.getDistributionCardNo(), oldShareUser.getCardNo())){
            shareUser = oldShareUser;
            bindUser = oldShareUser;
        } else {
            shareUser = distributionUserService.getByCardNo(orderItem.getDistributionCardNo());
            // 判断是否可以进行分销操作
            if(checkAmountOver(shareUser, orderItem)){
                return;
            }
            // 绑定绑定销售员信息
            ServerResponseEntity serverResponse = distributionBindUserService.bindDistribution(shareUser, orderItem.getUserId(), 1);
            if (serverResponse.isFail()) {
                log.info("绑定销售员信息失败，跳过分销流程,订单号：{}, 订单项Id：{}",orderItem.getOrderNumber(),orderItem.getOrderItemId());
            }
            // 绑定的用户
            bindUser = (DistributionUser) serverResponse.getData();
        }

//        // 没有开启分销员自购，也就是自己推广自己的东西没有收益
//        if (Objects.equals(shareUser.getUserId(), orderItem.getUserId()) && !Objects.equals(basicSet.getOwnBuyAward(), 1)) {
//            log.info("没有开启分销员自购，推广人不能自己哟");
//            // 推广人不能自己哟
//            return;
//        } else {
//            // 看看自己是不是分销员，如果没有开启分销员互购，自己是分销员推广人也没有收益
//            DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(orderItem.getUserId(), shareUser.getShopId());
//            // 下单的用户以前申请过分销员，但现在又不是了，所以就将分销员信息置空
//            if (distributionUser != null && !Objects.equals(distributionUser.getState(), 1)) {
//                distributionUser = null;
//            }
//
//            // 没有开启互购
//            if (!Objects.equals(basicSet.getParallelDeal(), 1) && distributionUser != null
//                    && !Objects.equals(distributionUser.getDistributionUserId(), shareUser.getDistributionUserId())) {
//                log.info("店铺没有开启互购，购买用户也已成为该店铺的推广员，无法被推广");
//                // 您已成为该店铺的推广员，无法被推广
//                return;
//            }
//        }
        //推广人若为永久封禁
        if (Objects.equals(shareUser.getState(),DistributionUserStateEnum.PER_BAN.getValue()) || Objects.equals(shareUser.getState(), DistributionUserStateEnum.BAN.getValue())){
            log.info("推广员已被暂时封禁或永久封禁");
            return;
        }
        // 添加收入流水记录并将收入添加到待结算金额到钱包中
        createIncomeByOrderItem(distributionConfigVO, shareUser, bindUser, orderItem);
    }

    /**
     * 创建订单项收入记录添加待结算金额到钱包中
     */
    private void createIncomeByOrderItem(DistributionConfigVO distributionConfigVO, DistributionUser shareUser, DistributionUser bindUser, OrderItem orderItem) {

        //判断是否会产生分销业绩
        if (Objects.isNull(bindUser) && Objects.isNull(shareUser)) {
            log.error("没有分享人，没有关系人，不产生业绩");
            return;
        }
        //获取该分销商品的设置数据
        DistributionProdPO distributionProdPo = distributionProdService.getDistributionProdPoByProdId(orderItem.getProdId());

        // 这件商品原本是分销商品被加入了购物车，后来又不是了
        if (distributionProdPo == null) {
            return;
        } else {
            distributionProdPo.setShopId(orderItem.getShopId());
            // 计算佣金，用实付金额计算
            distributionProdPo.setPrice(orderItem.getActualTotal());
        }
        //定义一个最终的业绩归属人变量
        DistributionUser finalDistributionUser;

        //判断是分享人优先还是关系链优先 0 允许绑定,关系优先,1,不绑定 分享人优先
        if (distributionConfigVO.getAttribution() == 0) {
            //关系链优先
            log.info("关系链优先,关系人获得业绩");
            finalDistributionUser = bindUser;
        } else {
            //分享人优先
            log.info("分享人优先,分享人获得业绩");
            finalDistributionUser = shareUser;
        }

        // 关系链优先时，用户扫了别的分销员二维码，
        // 前端传的分销员卡号不是该用户绑定分销员的卡号，所以要重新插入下
        orderItem.setDistributionCardNo(finalDistributionUser.getCardNo());

        if (finalDistributionUser == null) {
            log.info("没有找到业绩归属者");
            return;
        }

        // 判断是否可以进行分销操作
        if(checkAmountOver(finalDistributionUser, orderItem)){
            return;
        }

        DistributionUserIncome distributionUserIncome = new DistributionUserIncome();
        distributionUserIncome.setOrderNumber(orderItem.getOrderNumber());
        distributionUserIncome.setOrderItemId(orderItem.getOrderItemId());
        distributionUserIncome.setCreateTime(new Date());
        distributionUserIncome.setUpdateTime(new Date());

        //计算佣金金额
        DistributionAwardDataVO distributionAwardDataVO = distributionProdService.getAwardDataVO(distributionProdPo, finalDistributionUser.getDistributionUserId(),orderItem);


        //创建插入业绩记录对象
            // 直推奖励
        insertAwardNumber(orderItem, finalDistributionUser, distributionAwardDataVO, distributionUserIncome);

        //不使用默认奖励
        if (Objects.equals(distributionProdPo.getDefaultReward(),0)){
            //是否开启了上级奖励(0 关闭 1开启)
            if (!Objects.equals(distributionProdPo.getParentAwardSet(), 1)) {
                log.info("没有开启上级奖励");
                return;
            }
        }
        //获取上级id
        if (Objects.isNull(finalDistributionUser.getParentId()) && Objects.equals(distributionConfigVO.getAttribution(),0)) {
            log.info("无法获取推广员的上级id");
            return;
        }
        if(distributionAwardDataVO.getParentAwardNumber() == 0) {
            log.info("订单编号-{},商品id-{}：二级分销金额为0，不进行二级分销的操作", orderItem.getOrderNumber(), orderItem.getProdId());
            return;
        }
        // 需要失效记录注释
    /*    double totalAwardNumber = Arith.add(distributionAwardDataVO.getAwardNumber() ,distributionAwardDataVO.getParentAwardNumber());
        if(totalAwardNumber >= orderItem.getActualTotal()) {
            log.info("订单编号-{},商品id-{}：总分销金额大于等于实付金额，不进行二级分销的操作", orderItem.getOrderNumber(), orderItem.getProdId());
            return;
        }*/
        log.info("进入上级奖励流程");
        // 间推奖励
        insertParentAwardNumber(distributionConfigVO, orderItem, finalDistributionUser, bindUser, distributionAwardDataVO, distributionUserIncome);

    }

    /**
     * 检查分销金额是否超出订单项金额
     * @param finalDistributionUser
     * @param orderItem
     * @return
     */
    private boolean checkAmountOver(DistributionUser finalDistributionUser, OrderItem orderItem) {
        //获取该分销商品的设置数据
        DistributionProdPO distributionProdPo = distributionProdService.getDistributionProdPoByProdId(orderItem.getProdId());

        // 这件商品原本是分销商品被加入了购物车，后来又不是了
        if (distributionProdPo == null) {
            return true;
        } else {
            distributionProdPo.setShopId(orderItem.getShopId());
            // 计算佣金，用实付金额计算
            distributionProdPo.setPrice(orderItem.getActualTotal());
        }
        // 如果是没开启上级奖励，则上级比例为0
        if(Objects.equals(distributionProdPo.getParentAwardSet(),0)){
            distributionProdPo.setParentAwardNumbers(0.0);
        }

        return false;
    }

    /**
     *  实付金额小于佣金，修改收入订单为失效
     * @param orderItem
     * @param distributionAwardDataVO
     * @param distributionUserIncome
     * @param type 1直推 2间推
     */
    private void setDistributionIncome(OrderItem orderItem, DistributionAwardDataVO distributionAwardDataVO, DistributionUserIncome distributionUserIncome, int type){

        if (type == 1){
            if (distributionAwardDataVO.getAwardNumber()  >= orderItem.getActualTotal()) {
                log.info("直推 分销金额比实付金额要大，分销佣金收入记录改为失效订单");
                distributionUserIncome.setState(DistributionUserIncomeStateEnum.INVALID.getValue());
                distributionUserIncome.setReson(DistributionAudit.INCOME_ONE.getValue());
                return;
            }
        }else if (type == 2){
            if ((distributionAwardDataVO.getAwardNumber() + distributionAwardDataVO.getParentAwardNumber())  >= orderItem.getActualTotal()) {
                log.info("间推 分销金额比实付金额要大，分销佣金收入记录改为失效订单");
                distributionUserIncome.setState(DistributionUserIncomeStateEnum.INVALID.getValue());
                distributionUserIncome.setReson(DistributionAudit.INCOME_ONE.getValue());
                return;
            }
        }

        double incomeAmount = Arith.roundByBanker(distributionUserIncome.getIncomeAmount(), 2);
        // 分销佣金小于0.01
        if (incomeAmount < Constant.MIN_PRODUCT_AMOUNT) {
            if (Objects.nonNull(distributionUserIncome.getReson())){
                return;
            }
            distributionUserIncome.setIncomeAmount(Constant.ZERO_DOUBLE);
            distributionUserIncome.setReson(DistributionAudit.INCOME_THREE.getValue());
            distributionUserIncome.setState(DistributionUserIncomeStateEnum.INVALID.getValue());
            return;
        }
        // 如果系统设置为交易完毕后结算，则记录为结算状态，否则为未结算状态
        distributionUserIncome.setState(1);
    }

    private void insertAwardNumber(OrderItem orderItem, DistributionUser finalDistributionUser, DistributionAwardDataVO distributionAwardDataVO, DistributionUserIncome distributionUserIncome) {
        // 查询该推广员钱包信息
        DistributionUserWallet distributionUserWallet = distributionUserWalletService.getOne(new LambdaQueryWrapper<DistributionUserWallet>().eq(DistributionUserWallet::getDistributionUserId, finalDistributionUser.getDistributionUserId()));

        distributionUserIncome.setDistributionUserId(finalDistributionUser.getDistributionUserId());
        distributionUserIncome.setWalletId(distributionUserWallet.getWalletId());
        distributionUserIncome.setIncomeAmount(distributionAwardDataVO.getAwardNumber());
        // 若佣金大于实付金额改收入改为失效订单
        setDistributionIncome(orderItem, distributionAwardDataVO, distributionUserIncome, 1);

        // 收入类型为一级奖励
        distributionUserIncome.setIncomeType(1);
        distributionUserIncomeService.save(distributionUserIncome);

        // 订单项添加分佣奖励
        orderItem.setDistributionAmount(distributionUserIncome.getIncomeAmount());

        if (distributionUserIncome.getState().equals(DistributionUserIncomeStateEnum.UNCOMMISSION.getValue())){
            // 给钱包增加待结算金额
            distributionUserWallet.setUnsettledAmount(Arith.add(distributionUserWallet.getUnsettledAmount(), distributionAwardDataVO.getAwardNumber()));
            distributionUserWalletBillService.save(new DistributionUserWalletBill(distributionUserWallet, "客户支付获取待结算金额","Customer payment to obtain the amount to be settled", distributionAwardDataVO.getAwardNumber(), 0.0, 0.0, 0.0, 0));
        }else {
            log.info("增加失效佣金");
            // 给钱包增加待失效金额
            distributionUserWallet.setInvalidAmount(Arith.add(distributionUserWallet.getInvalidAmount(), distributionUserIncome.getIncomeAmount()));
            if (distributionUserIncome.getIncomeAmount() != 0){
                distributionUserWalletBillService.save(new DistributionUserWalletBill(distributionUserWallet, "客户支付小于佣金失效增加金额","The client pays less than the increase in commission lapse", 0.0, 0.0, distributionUserIncome.getIncomeAmount(), 0.0, 0));
            }
            // 佣金失效后，订单中分销金额要清除（如果不清除，失效的分销金额会插入到订单项中，就参与了订单金额的计算）
            orderItem.setDistributionAmount(null);
        }

        //更新钱包
        boolean distributionUserWalletUpdateSuccess = distributionUserWalletService.updateById(distributionUserWallet);

        if (!distributionUserWalletUpdateSuccess) {
            // 更新推广员钱包信息失败
            throw new YamiShopBindException("yami.cannot.distribution.update.wallet");
        }
    }

    private void insertParentAwardNumber(DistributionConfigVO distributionConfigVO,OrderItem orderItem, DistributionUser finalDistributionUser,DistributionUser bindUser,
                                         DistributionAwardDataVO distributionAwardDataVO, DistributionUserIncome distributionUserIncome) {
        //添加二级佣金给上级邀请人
        DistributionUserWallet parentDistributionUserWallet = distributionUserWalletService.getOne(new LambdaQueryWrapper<DistributionUserWallet>().eq(DistributionUserWallet::getDistributionUserId, finalDistributionUser.getParentId()));
        if (Objects.isNull(parentDistributionUserWallet)) {
            log.info("分销员id-{}：没有钱包信息", finalDistributionUser.getParentId());
            return;
        }
        //如果上级不为空,则创建上级奖励业绩记录
        distributionUserIncome.setIncomeId(null);
        distributionUserIncome.setIncomeType(2);
        distributionUserIncome.setDistributionUserId(parentDistributionUserWallet.getDistributionUserId());
        distributionUserIncome.setIncomeAmount(distributionAwardDataVO.getParentAwardNumber());
        distributionUserIncome.setWalletId(parentDistributionUserWallet.getWalletId());
        // 若佣金大于实付金额改收入改为失效订单
        setDistributionIncome(orderItem, distributionAwardDataVO, distributionUserIncome, 2);
        //类型为二级奖励
        distributionUserIncomeService.save(distributionUserIncome);

        if (distributionUserIncome.getState().equals(DistributionUserIncomeStateEnum.UNCOMMISSION.getValue())){
            //给邀请人钱包增加待结算金额
            parentDistributionUserWallet.setUnsettledAmount(Arith.add(parentDistributionUserWallet.getUnsettledAmount(), distributionAwardDataVO.getParentAwardNumber()));
            //增加钱包流水记录
            if(distributionAwardDataVO.getParentAwardNumber() != 0) {
                distributionUserWalletBillService.save(new DistributionUserWalletBill(parentDistributionUserWallet, "间推奖励", "Second-generation rewards",distributionAwardDataVO.getParentAwardNumber(), 0.0, 0.0, 0.0, 0));
            }
            // 订单项添加上级奖励
            orderItem.setDistributionParentAmount(distributionUserIncome.getIncomeAmount());
        }else {
            log.info("增加失效佣金");
            //给邀请人钱包增加失效金额
            parentDistributionUserWallet.setInvalidAmount(Arith.add(parentDistributionUserWallet.getInvalidAmount(), distributionUserIncome.getIncomeAmount()));
            //增加钱包流水记录
            if(distributionAwardDataVO.getParentAwardNumber() != 0) {
                distributionUserWalletBillService.save(new DistributionUserWalletBill(parentDistributionUserWallet, "间推奖励失效", "Intermittent bonuses are void", 0.0, 0.0, distributionUserIncome.getIncomeAmount(),0.0, 0));
            }
            //佣金失效后，订单中分销金额要清除（如果不清除，失效的分销金额会插入到订单项中，就参与了订单金额的计算）
            orderItem.setDistributionParentAmount(null);
        }


        //更新邀请人钱包
        boolean parentDistributionUserWalletUpdateSuccess = distributionUserWalletService.updateById(parentDistributionUserWallet);
        if (!parentDistributionUserWalletUpdateSuccess) {
            // 更新推广员钱包信息失败
            throw new YamiShopBindException("yami.cannot.distribution.update.wallet");
        }
    }

    /**
     * 当该商品是用户分享时，检查是否能给该用户产生收益
     * @param orderItem 订单项
     * @param distributionConfigVO 分销绑定条件设置
     * @return true: 可以，false：不可以
     */
    private boolean checkSelfShare(OrderItem orderItem, DistributionConfigVO distributionConfigVO) {
        if (Objects.isNull(orderItem)) {
            return true;
        }
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(orderItem.getUserId(), Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            // 用户不是分销员
            return true;
        }
        if (StrUtil.isBlank(orderItem.getDistributionCardNo()) || !Objects.equals(distributionUser.getCardNo(), orderItem.getDistributionCardNo())) {
            // 订单没有分销信息或者分销信息不是当前用户的链接
            return true;
        }
        if (Objects.equals(distributionConfigVO.getAttribution(),1)) {
            //不绑定，分享人优先
            return true;
        }
        // 查询该用户绑定的分享人
        DistributionUserBind distributionUserBind = distributionUserBindMapper.selectOne(new LambdaQueryWrapper<DistributionUserBind>()
                .eq(DistributionUserBind::getShopId, Constant.PLATFORM_SHOP_ID)
                .eq(DistributionUserBind::getState, 1)
                .eq(DistributionUserBind::getUserId, orderItem.getUserId())
        );
//        if (Objects.nonNull(distributionUserBind)) {
//            // 判断是否处于保存期内
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(distributionUserBind.getBindTime());
//            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + distributionBindSet.getProtectDay());
//            if (calendar.getTime().after(new Date())) {
//                // 用户处于保护期内，无法通过自己分享的链接产生个人收益
//                isSelfIncome = false;
//            }
//            return false;
//        }
        return Objects.isNull(distributionUserBind);
    }

}
